<template>
  <div class="flex justify-between mb-10px">
    <div>
      <span class="mr-10px">订阅协议：</span>
      <Select v-model:value="protocol" :allowClear="true" class="mr-10px" placeholder="订阅协议" style="width: 200px">
        <SelectOption value="sms">短信</SelectOption>
        <SelectOption value="email">邮件</SelectOption>
      </Select>

      <span class="mr-10px">订阅状态：</span>

      <Select v-model:value="status" :allowClear="true" class="mr-10px" placeholder="订阅状态" style="width: 200px">
        <SelectOption value="0">未确认</SelectOption>
        <SelectOption value="1">已确认</SelectOption>
        <SelectOption value="3">已取消确认</SelectOption>
      </Select>

      <span class="mr-10px">订阅终端：</span>

      <Input v-model:value="endpoint" class="mr-10px" placeholder="订阅终端" style="width: 240px" />

      <Button class="mr-10px" @click="handleReset">重置</Button>
      <Button type="primary" @click="getSubList">查询</Button>
    </div>
    <div>
      <Button v-per="'add'" type="primary" @click="addDrawer">新增订阅</Button>
    </div>
  </div>
  <div>
    <Table
      :columns="detailsColumns"
      :dataSource="dataSource"
      :loading="loading"
      :pagination="pagination"
      :scroll="scroll"
      bordered
      class="main-table"
      show-size-changer
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operation'">
          <Button v-per="'request'" :disabled="record.status === '已确认'" type="link" @click="onAdd(record)"
            >请求订阅</Button
          >
          <Divider type="vertical" />
          <span v-per="'delete'">
            <Popconfirm cancel-text="取消" ok-text="确认" title="确定要删除吗?" @confirm="onDelete(record.subUrn)">
              <Button type="link">删除</Button>
            </Popconfirm>
          </span>
        </template>
      </template>
    </Table>
    <SubscriptionDrawer ref="subDrawerRef" v-bind="subProps" @closeSubDrawer="closeSubDrawer"></SubscriptionDrawer>
  </div>
</template>
<script lang="ts" setup>
import { Button, Divider, Input, message, Popconfirm, Select, SelectOption, Table, TableProps } from 'ant-design-vue';
import { detailsColumns } from '/@/views/maintenance-center/message-theme/components/topic';
import { computed, ref } from 'vue';
import {
  deleteSubscription,
  getSubscriptionList,
  requestSubscription,
  selectTopicList,
} from '/@/api/maintenance-center/message-notification/messageNotification';
import { form } from '/@/views/maintenance-center/message-subscription/components/subscription';
import { SubscriptionItem } from '/@/api/maintenance-center/message-notification/model/messageNotificationModel';
import SubscriptionDrawer from '/@/views/maintenance-center/message-theme/subscriptionDrawer.vue';

const scroll = ref<undefined | object>(undefined);
const dataSource = ref<SubscriptionItem[]>([]);
const loading = ref(true);
let total = ref(0);
let protocol = ref('');
let status = ref('');
let endpoint = ref('');
// 分页
const pagination = computed(() => ({
  showSizeChanger: true,
  current: form.current,
  pageSize: form.size,
  total: total.value,
  pageSizeOptions: [5, 10, 20, 30, 40, 100],
  showTotal: () => {
    return `共 ${total.value} 条`;
  },
}));

async function getSubList() {
  form.protocol = protocol.value;
  form.status = status.value;
  form.endpoint = endpoint.value;
  try {
    await getSubscriptionList(form).then((res) => {
      dataSource.value = res.items;
      total.value = res.total;
    });
  } finally {
    loading.value = false;
  }
}

// 重置
async function handleReset() {
  protocol.value = '';
  status.value = '';
  endpoint.value = '';
  await getSubList();
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.value.current = Number(pag.current);
  pagination.value.pageSize = Number(pag.pageSize);
  if (Number(pagination.value.pageSize) > 10) {
    scroll.value = { y: 500 };
  }
  form.size = Number(pag.pageSize);
  form.current = Number(pag.current);
  getSubList();
};
// 新增订阅
const subProps = ref({
  visible: false,
  drawerType: '',
  title: '',
  selectOptions: {},
});

async function addDrawer() {
  await selectTopicList()
    .then((res) => {
      subProps.value.selectOptions = res;
      return subProps.value.selectOptions;
    })
    .catch((e) => {
      message.error('主题列表查询失败：' + e.response.data.msg);
    });
  subProps.value.drawerType = 'subscript';
  subProps.value.title = '添加订阅';
  subProps.value.visible = true;
}

const closeSubDrawer = () => {
  subProps.value.visible = false;
  getSubList();
};
// 删除
const onDelete = (subURN: string) => {
  const param = {
    subUrn: subURN,
  };
  deleteSubscription(param)
    .then(() => {
      message.success('删除订阅成功');
    })
    .catch((e) => {
      message.error('删除失败：' + e.response.data.msg);
    });
  getSubList();
};
// 请求订阅
const onAdd = (record: Recordable) => {
  const params = {
    subUrn: record.subUrn,
    endpoint: record.endpoint,
    protocol: record.protocol,
  };
  requestSubscription(params)
    .then(() => {
      message.success('请求订阅成功');
    })
    .catch((e) => {
      message.error('请求订阅失败：' + e.response.data.msg);
    });
  getSubList();
};
getSubList();
</script>
